package cn.com.twoke.application.game.mario.game.config;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.InputStream;

/**
 * 配置加载器
 */
public class ConfigLoader {
    
    private static final String CONFIG_FILE = "config/game-config.json";
    
    /**
     * 加载游戏配置
     * @return GameConfig实例
     */
    public static GameConfig loadConfig() {
        GameConfig config = GameConfig.getInstance();
        
        try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(CONFIG_FILE)) {
            if (is != null) {
                String configContent = IoUtil.readUtf8(is);
                JSONObject json = JSONUtil.parseObj(configContent);
                
                // 物理系统配置
                if (json.containsKey("physics")) {
                    JSONObject physics = json.getJSONObject("physics");
                    config.setGravity(physics.getFloat("gravity", config.getGravity()));
                    config.setCollisionTolerance(physics.getFloat("collisionTolerance", config.getCollisionTolerance()));
                    config.setFixedTimeStep(physics.getFloat("fixedTimeStep", config.getFixedTimeStep()));
                }
                
                // 渲染系统配置
                if (json.containsKey("rendering")) {
                    JSONObject rendering = json.getJSONObject("rendering");
                    config.setTargetFps(rendering.getInt("targetFps", config.getTargetFps()));
                }
                
                // 玩家配置
                if (json.containsKey("player")) {
                    JSONObject player = json.getJSONObject("player");
                    config.setPlayerMoveSpeed(player.getFloat("moveSpeed", config.getPlayerMoveSpeed()));
                    config.setPlayerJumpForce(player.getFloat("jumpForce", config.getPlayerJumpForce()));
                    config.setPlayerCoyoteTime(player.getFloat("coyoteTime", config.getPlayerCoyoteTime()));
                }
                
                // 场景配置
                if (json.containsKey("scene")) {
                    JSONObject scene = json.getJSONObject("scene");
                    config.setSceneWidth(scene.getInt("width", config.getSceneWidth()));
                    config.setSceneHeight(scene.getInt("height", config.getSceneHeight()));
                    config.setDebugSceneWidth(scene.getInt("debugWidth", config.getDebugSceneWidth()));
                    config.setDebugSceneHeight(scene.getInt("debugHeight", config.getDebugSceneHeight()));
                }
            }
        } catch (Exception e) {
            // 配置加载失败时使用默认值
            System.err.println("Failed to load game config, using defaults: " + e.getMessage());
        }
        
        return config;
    }
}